<template>
  <div>
    <a-input-search
      v-model="selectedMaterialNames"
      :placeholder="placeholder"
      :disabled="disabled"
      readOnly
      @search="handleSearch">
      <a-button slot="enterButton" :disabled="disabled">选择</a-button>
    </a-input-search>
    <a-modal
      :title="title"
      :width="modalWidth"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel">
      
      <a-spin :spinning="confirmLoading">
        <!-- 查询区域 -->
        <div class="query-area">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :md="8" :sm="12">
                <a-form-item :label="materialCodeLabel">
                  <a-input :placeholder="`请输入${materialCodeLabel}`" v-model="queryParam.materialCode" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <a-form-item :label="materialNameLabel">
                  <a-input :placeholder="`请输入${materialNameLabel}`" v-model="queryParam.materialName" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
                  <a-button type="primary" style="margin-left: 8px" @click="handleAdd" icon="plus">添加</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        
        <!-- 表格区域 -->
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :scroll="{ x: 1200 }"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: internalMultiple ? 'checkbox' : 'radio'}"
          :customRow="customRowClick"
          @change="handleTableChange">
          
          <template slot="materialImageSlot" slot-scope="text">
            <div v-if="text" class="material-thumbnail-container">
              <img
                v-if="isImageFile(text)"
                :src="getImageUrl(text)"
                class="material-thumbnail"
                alt="物料图片"
                @error="handleImageError"
              />
              <a-icon v-else type="file-pdf" class="file-icon" />
            </div>
            <span v-else>-</span>
          </template>
          
          <template slot="statusSlot" slot-scope="text">
            <a-tag :color="text == '0' ? 'green' : 'red'">
              <j-dict-label :value="text" dictCode="wms_material_status"/>
            </a-tag>
          </template>
          
          <template slot="unitCostSlot" slot-scope="text">
            <span>{{ text ? text.toFixed(2) : '-' }}</span>
          </template>
        </a-table>
      </a-spin>
    </a-modal>
    
    <!-- 添加物料模态框 -->
    <profile-modal ref="profileModal" @ok="modalFormOk" v-if="type === '1'"></profile-modal>
    <fitting-modal ref="fittingModal" @ok="modalFormOk" v-if="type === '2'"></fitting-modal>
    <auxiliary-modal ref="auxiliaryModal" @ok="modalFormOk" v-if="type === '3'"></auxiliary-modal>
    <other-modal ref="otherModal" @ok="modalFormOk" v-if="type === '4'"></other-modal>
  </div>
</template>

<script>
  import { getAction } from '@/api/manage'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import JDictLabel from '@/components/dict/JDictLabel'
  import { getFileAccessHttpUrl } from '@/api/manage'
  import debounce from 'lodash/debounce'
  import ProfileModal from '@/views/wms/material/modules/ProfileModal'
  import FittingModal from '@/views/wms/material/modules/FittingModal'
  import AuxiliaryModal from '@/views/wms/material/modules/AuxiliaryModal'
  import OtherModal from '@/views/wms/material/modules/OtherModal'

  export default {
    name: 'JSelectMaterial',
    components: {
      JDictSelectTag,
      JDictLabel,
      ProfileModal,
      FittingModal,
      AuxiliaryModal,
      OtherModal
    },
    props: {
      placeholder: {
        type: String,
        default: '请选择物料',
        required: false
      },
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      value: {
        type: [String, Array],
        required: false
      },
      multiple: {
        type: Boolean,
        default: false,
        required: false
      },
      mode: {
        type: String,
        default: 'default',
        required: false,
        validator: (value) => {
          return ['default', 'multiple'].includes(value);
        }
      },
      type: {
        type: String,
        default: '',
        required: false
      },
      modalWidth: {
        type: Number,
        default: 1000,
        required: false
      },
      title: {
        type: String,
        default: '选择物料',
        required: false
      }
    },
    data() {
      return {
        visible: false,
        confirmLoading: false,
        selectedRowKeys: [],
        selectedMaterialKeys: [], // 保存选择的物料ID
        selectedMaterialNames: '', // 保存选择的物料名称
        selectedMaterials: [], // 保存选择的物料信息
        internalMultiple: this.multiple, // 内部使用的多选标志
        
        // 查询条件
        queryParam: {
          materialCode: '',
          materialName: '',
          materialType: ''
        },
        
        // 数据源
        dataSource: [],
        
        // 表格列
        columns: [],
        
        // 分页参数
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        
        loading: false,
        url: {
          list: '/wms/material/list',
          queryById: '/wms/material/queryById',
        }
      }
    },
    computed: {
      materialCodeLabel() {
        switch (this.type) {
          case '1': return '型材编号';
          case '2': return '配件编号';
          case '3': return '辅件编号';
          case '4': return '物料编号';
          default: return '物料编号';
        }
      },
      materialNameLabel() {
        switch (this.type) {
          case '1': return '型材名称';
          case '2': return '配件名称';
          case '3': return '辅件名称';
          case '4': return '物料名称';
          default: return '物料名称';
        }
      }
    },
    watch: {
      value: {
        immediate: true,
        handler(val) {
          if (val) {
            this.initSelectedMaterial(val);
          } else {
            this.selectedMaterialKeys = [];
            this.selectedMaterialNames = '';
            this.selectedMaterials = [];
            this.selectedRowKeys = [];
          }
        }
      },
      type: {
        immediate: true,
        handler(val) {
          if (val) {
            this.queryParam.materialType = val;
            this.initColumns();
          }
        }
      },
      mode: {
        immediate: true,
        handler(val) {
          this.internalMultiple = val === 'multiple';
        }
      },
      multiple: {
        immediate: true,
        handler(val) {
          this.internalMultiple = val;
        }
      }
    },
    created() {
      this.initColumns();
    },
    methods: {
      // 初始化表格列
      initColumns() {
        // 公共列
        const commonColumns = [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: this.materialCodeLabel,
            align: 'center',
            dataIndex: 'materialCode',
            width: 120
          },
          {
            title: this.materialNameLabel,
            align: 'center',
            dataIndex: 'materialName',
            width: 150
          },
          {
            title: '物料图片',
            align: 'center',
            dataIndex: 'materialImage',
            width: 80,
            scopedSlots: { customRender: 'materialImageSlot' }
          },
          {
            title: '规格型号',
            align: 'center',
            dataIndex: 'specification',
            width: 120
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'unit',
            width: 80
          },
          {
            title: '单位成本',
            align: 'center',
            dataIndex: 'unitCost',
            width: 100,
            scopedSlots: { customRender: 'unitCostSlot' }
          },
          {
            title: '状态',
            align: 'center',
            dataIndex: 'status',
            width: 80,
            scopedSlots: { customRender: 'statusSlot' }
          }
        ];
        
        // 根据类型添加特定列
        let specificColumns = [];
        
        switch (this.type) {
          case '1': // 型材
            specificColumns = [
              {
                title: '颜色',
                align: 'center',
                dataIndex: 'color',
                width: 80
              },
              {
                title: '长度(mm)',
                align: 'center',
                dataIndex: 'length',
                width: 100
              },
              {
                title: '宽度(mm)',
                align: 'center',
                dataIndex: 'width',
                width: 100
              },
              {
                title: '高度(mm)',
                align: 'center',
                dataIndex: 'height',
                width: 100
              },
              {
                title: '重量',
                align: 'center',
                dataIndex: 'weight',
                width: 80
              }
            ];
            break;
          case '2': // 配件
          case '3': // 辅件
            specificColumns = [
              {
                title: '颜色',
                align: 'center',
                dataIndex: 'color',
                width: 80
              },
              {
                title: '品牌',
                align: 'center',
                dataIndex: 'brand',
                width: 100
              }
            ];
            break;
          case '4': // 其他
            specificColumns = [
              {
                title: '品牌',
                align: 'center',
                dataIndex: 'brand',
                width: 100
              },
              {
                title: '备注',
                align: 'center',
                dataIndex: 'remark',
                width: 150
              }
            ];
            break;
          default:
            break;
        }
        
        this.columns = [...commonColumns, ...specificColumns];
      },
      
      // 自定义行点击事件
      customRowClick(record) {
        return {
          onClick: () => {
            this.handleRowClick(record);
          }
        };
      },
      
      // 初始化已选择的物料信息
      initSelectedMaterial(selectedIds) {
        if (!selectedIds) return;
        
        this.loading = true;
        let params = { ids: selectedIds };
        
        getAction(this.url.queryById, params).then(res => {
          if (res.success) {
            this.selectedMaterials = res.result || [];
            this.selectedMaterialKeys = this.selectedMaterials.map(item => item.id);
            this.selectedMaterialNames = this.selectedMaterials.map(item => item.materialName).join(',');
            this.selectedRowKeys = this.selectedMaterialKeys;
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 打开选择框
      handleSearch() {
        if (this.disabled) return;
        
        this.visible = true;
        this.loadData(1);
      },
      
      // 加载数据
      loadData(arg) {
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        
        const params = this.getQueryParams();
        this.loading = true;
        
        getAction(this.url.list, params).then(res => {
          if (res.success) {
            this.dataSource = res.result.records || [];
            this.ipagination.total = res.result.total || 0;
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 获取查询参数
      getQueryParams() {
        const param = Object.assign({}, this.queryParam);
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return param;
      },
      
      // 选择改变
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        
        if (!this.internalMultiple && this.mode !== 'multiple') {
          this.selectedMaterials = selectedRows;
        } else {
          // 保持已经选择的和当前页面选择的
          const selectedIds = selectedRows.map(row => row.id);
          this.selectedMaterials = this.selectedMaterials.filter(item => {
            return selectedIds.includes(item.id) || !this.dataSource.map(row => row.id).includes(item.id);
          });
          
          // 添加当前页面新选择的
          selectedRows.forEach(row => {
            const exist = this.selectedMaterials.some(item => item.id === row.id);
            if (!exist) {
              this.selectedMaterials.push(row);
            }
          });
        }
      },
      
      // 查询按钮
      searchQuery() {
        this.loadData(1);
      },
      
      // 重置按钮
      searchReset() {
        this.queryParam = {
          materialCode: '',
          materialName: '',
          materialType: this.type
        };
        this.loadData(1);
      },
      
      // 表格分页、排序、筛选变化
      handleTableChange(pagination, filters, sorter) {
        this.ipagination.current = pagination.current;
        this.ipagination.pageSize = pagination.pageSize;
        this.loadData();
      },
      
      // 处理行点击事件
      handleRowClick(record) {
        // 获取当前行的key
        const rowKey = record.id;
        
        // 根据是否多选处理不同的逻辑
        const isMultiple = this.internalMultiple || this.mode === 'multiple';
        
        if (!isMultiple) {
          // 单选模式：直接设置当前行为选中状态
          this.selectedRowKeys = [rowKey];
          this.selectedMaterials = [record];
        } else {
          // 多选模式：切换选中状态
          const index = this.selectedRowKeys.indexOf(rowKey);
          if (index === -1) {
            // 如果未选中，则添加到选中列表
            this.selectedRowKeys.push(rowKey);
            
            // 检查记录是否已存在于selectedMaterials中
            const exist = this.selectedMaterials.some(item => item.id === record.id);
            if (!exist) {
              this.selectedMaterials.push(record);
            }
          } else {
            // 如果已选中，则从选中列表移除
            this.selectedRowKeys.splice(index, 1);
            
            // 从selectedMaterials中移除
            const materialIndex = this.selectedMaterials.findIndex(item => item.id === record.id);
            if (materialIndex !== -1) {
              this.selectedMaterials.splice(materialIndex, 1);
            }
          }
        }
      },
      
      // 确定按钮
      handleOk() {
        this.selectedMaterialKeys = this.selectedMaterials.map(item => item.id);
        this.selectedMaterialNames = this.selectedMaterials.map(item => item.materialName).join(',');
        
        const isMultiple = this.internalMultiple || this.mode === 'multiple';
        const selectedIds = isMultiple ? this.selectedMaterialKeys.join(',') : (this.selectedMaterialKeys[0] || '');
        
        this.$emit('input', selectedIds);
        this.$emit('change', selectedIds, this.selectedMaterials);
        
        // 如果设置了回调函数，直接调用
        if (this.onMaterialSelected && typeof this.onMaterialSelected === 'function') {
          this.onMaterialSelected(selectedIds, this.selectedMaterials);
        }
        
        this.handleCancel();
      },
      
      // 取消按钮
      handleCancel() {
        this.visible = false;
      },
      
      // 添加物料
      handleAdd() {
        switch (this.type) {
          case '1':
            this.$refs.profileModal.add();
            break;
          case '2':
            this.$refs.fittingModal.add();
            break;
          case '3':
            this.$refs.auxiliaryModal.add();
            break;
          case '4':
            this.$refs.otherModal.add();
            break;
          default:
            this.$message.warning('请先选择物料类型');
            break;
        }
      },
      
      // 模态框确认回调
      modalFormOk() {
        this.loadData();
      },
      
      // 获取图片URL
      getImageUrl(text) {
        if (!text) return '';
        try {
          return getFileAccessHttpUrl(text);
        } catch (error) {
          console.error('获取文件URL失败:', error);
          return '';
        }
      },
      
      // 检查是否为图片文件
      isImageFile(url) {
        if (!url) return false;
        return /\.(jpg|jpeg|png|gif|bmp)$/i.test(url);
      },
      
      // 处理图片加载错误
      handleImageError(e) {
        console.error('图片加载失败:', e);
        e.target.src = '';
        e.target.alt = '图片加载失败';
      }
    }
  }
</script> 

<style scoped>
  .query-area {
    margin-bottom: 16px;
  }
  
  .material-thumbnail-container {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .material-thumbnail {
    max-width: 40px;
    max-height: 40px;
    object-fit: contain;
  }
  
  .file-icon {
    font-size: 24px;
    color: #1890ff;
  }
  
  /* 添加鼠标悬停样式，提升用户体验 */
  :deep(.ant-table-tbody > tr) {
    cursor: pointer;
  }
  
  :deep(.ant-table-tbody > tr:hover) {
    background-color: #e6f7ff;
  }
  
  /* 表格滚动条样式优化 */
  :deep(.ant-table-body) {
    overflow-x: auto !important;
  }
  
  :deep(.ant-table-header) {
    overflow: hidden !important;
    margin-bottom: 0 !important;
    padding-bottom: 0 !important;
  }
</style> 